package cn.tedu.boot2.controller;

import cn.tedu.boot2.entity.User;
import cn.tedu.boot2.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@RestController
public class UserController {

    @RequestMapping("/reg")
    public String reg(User user){
        try(Connection conn = DBUtil.getConnection()){
            String sql = "SELECT id FROM user WHERE username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                return "用户名已存在";
            }
            String sql2 = "INSERT INTO user VALUES(NULL,?,?,?);";
            PreparedStatement ps2 = conn.prepareStatement(sql2);
            ps2.setString(1,user.getUsername());
            ps2.setString(2,user.getPassword());
            ps2.setString(3,user.getNickname());

            ps2.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功！<a href='/'>返回首页</a>";
    }

    @RequestMapping("/login")
    public String login(User user){

        try(Connection conn = DBUtil.getConnection()){
            String sql = "SELECT password FROM user WHERE username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String pw = rs.getString(1);
                if(pw.equals(user.getPassword())){
                    return "登录成功";
                }
                return "密码错误";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return "用户名不存在！";
    }
}
